import React, { useEffect, useState } from 'react'
import { Card, Typography, Row, Col, Statistic, Table, Progress, Tabs } from 'antd'
import { useRouter } from 'next/router'
import { 
  ThunderboltOutlined, 
  CarOutlined,
  AlertOutlined,
  SettingOutlined
} from '@ant-design/icons'
import MainLayout from '../components/layout/MainLayout'

const { Title } = Typography
const { TabPane } = Tabs

export default function Dashboard() {
  const router = useRouter()
  const [stats, setStats] = useState({
    devices: { total: 156, online: 142, offline: 14, warning: 3 },
    energy: { todayConsumption: 2847.5, monthlyConsumption: 85420.3, efficiency: 92.5, cost: 12847.2 },
    parking: { total: 500, occupied: 387, available: 113, revenue: 15420.5 },
    security: { alerts: 2, incidents: 0, cameras: 24, accessPoints: 12 },
    personnel: { total: 45, present: 38, absent: 7, visitors: 12 }
  })
  const [loading, setLoading] = useState(false)

  // 设备列表数据
  const deviceData = [
    { id: 1, name: '主入口闸机', type: '闸机', location: 'A区入口', status: '在线', lastUpdate: '2024-01-10' },
    { id: 2, name: '停车场闸机', type: '闸机', location: 'B区停车场', status: '在线', lastUpdate: '2024-01-06' },
    { id: 3, name: '监控摄像头01', type: '摄像头', location: 'C区楼梯', status: '离线', lastUpdate: '2024-01-05' },
    { id: 4, name: '环境传感器', type: '传感器', location: 'D区办公室', status: '在线', lastUpdate: '2024-01-12' },
    { id: 5, name: '消防报警器', type: '报警器', location: 'E区仓库', status: '维修中', lastUpdate: '2024-01-15' }
  ]

  // 告警数据
  const alertData = [
    { id: 1, title: '温度过高警告', device: '环境传感器', level: '中', time: '2024-01-15 14:30', status: '未处理' },
    { id: 2, title: '未授权访问', device: '门禁系统', level: '高', time: '2024-01-14 09:15', status: '已处理' }
  ]

  useEffect(() => {
    // 检查登录状态
    if (typeof window !== 'undefined') {
      const token = localStorage.getItem('token')
      if (!token) {
        router.push('/login')
        return
      }
    }

    // 模拟数据加载
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
    }, 500)
  }, [router])

  // 设备列表列定义
  const deviceColumns = [
    { title: '设备名称', dataIndex: 'name', key: 'name' },
    { title: '设备类型', dataIndex: 'type', key: 'type' },
    { title: '位置', dataIndex: 'location', key: 'location' },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status) => {
        let color = 'green'
        if (status === '离线') color = 'red'
        if (status === '维修中') color = 'orange'
        return <span style={{ color }}>{status}</span>
      }
    },
    { title: '上次更新', dataIndex: 'lastUpdate', key: 'lastUpdate' }
  ]

  return (
    <MainLayout>
      <Title level={3}>仪表盘</Title>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="设备总数"
              value={stats.devices.total}
              valueStyle={{ color: '#1890ff' }}
              prefix={<SettingOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <span style={{ color: 'green' }}>在线: {stats.devices.online}</span>
              <span style={{ color: 'red', marginLeft: 16 }}>离线: {stats.devices.offline}</span>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日能耗"
              value={stats.energy.todayConsumption}
              precision={1}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ThunderboltOutlined />}
              suffix="kWh"
            />
            <div style={{ marginTop: 8 }}>
              <span>效率: {stats.energy.efficiency}%</span>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="停车位"
              value={stats.parking.available}
              valueStyle={{ color: '#1890ff' }}
              prefix={<CarOutlined />}
              suffix={`/ ${stats.parking.total}`}
            />
            <div style={{ marginTop: 8 }}>
              <Progress 
                percent={Math.round((stats.parking.occupied / stats.parking.total) * 100)} 
                showInfo={false} 
                strokeColor="#1890ff" 
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="安全警报"
              value={stats.security.alerts}
              valueStyle={{ color: stats.security.alerts > 0 ? '#cf1322' : '#3f8600' }}
              prefix={<AlertOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <span>摄像头: {stats.security.cameras}个</span>
            </div>
          </Card>
        </Col>
      </Row>
      
      {/* 设备和告警信息 */}
      <Tabs defaultActiveKey="1">
        <TabPane tab="设备状态" key="1">
          <Card>
            <Table 
              columns={deviceColumns} 
              dataSource={deviceData} 
              rowKey="id"
              pagination={false}
              loading={loading}
            />
          </Card>
        </TabPane>
        <TabPane tab="告警信息" key="2">
          <Card>
            <Table 
              columns={[
                { title: '告警标题', dataIndex: 'title', key: 'title' },
                { title: '设备', dataIndex: 'device', key: 'device' },
                { 
                  title: '级别', 
                  dataIndex: 'level', 
                  key: 'level',
                  render: (level) => {
                    let color = 'green'
                    if (level === '中') color = 'orange'
                    if (level === '高') color = 'red'
                    return <span style={{ color }}>{level}</span>
                  }
                },
                { title: '时间', dataIndex: 'time', key: 'time' },
                { title: '状态', dataIndex: 'status', key: 'status' }
              ]} 
              dataSource={alertData} 
              rowKey="id"
              pagination={false}
              loading={loading}
            />
          </Card>
        </TabPane>
      </Tabs>
    </MainLayout>
  )
}
